package com.yami.shop.multishop.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.model.ShopDivisionReceiver;
import com.yami.shop.bean.model.ShopDivisionReceiverGroup;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ShopDivisionReceiverGroupService;
import com.yami.shop.service.ShopDivisionReceiverService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Tag(name = "分账管理（收款账号）")
@RestController
@AllArgsConstructor
@RequestMapping("/shop/divisionReceivers")
public class ShopDivisionReceiverController {
    private final ShopDivisionReceiverGroupService shopDivisionReceiverGroupService;

    private final ShopDivisionReceiverService shopDivisionReceiverService;

    public static final byte YES = 1;


    @GetMapping("/page")
    @Operation(summary = "分页查询店铺分账管理（账号组）", description = "分页查询店铺分账管理（账号组）")
    public ServerResponseEntity<IPage<ShopDivisionReceiver>> getShopWalletLogPage(PageParam<ShopDivisionReceiver> page, @ParameterObject ShopDivisionReceiver shopDivisionReceiver) {
        LambdaQueryWrapper<ShopDivisionReceiver> condition = new LambdaQueryWrapper<>();
        condition.eq(ShopDivisionReceiver::getShopId,SecurityUtils.getShopUser().getShopId());
        if(shopDivisionReceiver.getReceiverId() != null){
            condition.eq(ShopDivisionReceiver::getReceiverId, shopDivisionReceiver.getReceiverId());
        }

        if(StringUtils.isNotEmpty(shopDivisionReceiver.getReceiverAlias())){
            condition.like(ShopDivisionReceiver::getReceiverAlias, shopDivisionReceiver.getReceiverAlias());
        }

        if(shopDivisionReceiver.getReceiverGroupId() != null){
            condition.eq(ShopDivisionReceiver::getReceiverGroupId, shopDivisionReceiver.getReceiverGroupId());
        }

        if(StringUtils.isNotEmpty(shopDivisionReceiver.getReceiverGroupName())){
            condition.like(ShopDivisionReceiver::getReceiverGroupName, shopDivisionReceiver.getReceiverGroupName());
        }
        if(StringUtils.isNotEmpty(shopDivisionReceiver.getAccName())){
            condition.like(ShopDivisionReceiver::getAccName, shopDivisionReceiver.getAccName());
        }

        if(shopDivisionReceiver.getState() != null){
            condition.eq(ShopDivisionReceiver::getState, shopDivisionReceiver.getState());
        }
        IPage<ShopDivisionReceiver> pages = shopDivisionReceiverService.page(page, condition);
        return ServerResponseEntity.success(pages);
    }


    @Operation(summary = "收款账号详情", description = "收款账号详情")
    @Parameter(name = "recordId", description = "分账接收者ID", required = true)
    @GetMapping(value="/{recordId}")
    public ServerResponseEntity<ShopDivisionReceiver> detail(@PathVariable("recordId") Long recordId) {
        ShopDivisionReceiver record = shopDivisionReceiverService
                .getOne(new LambdaQueryWrapper<ShopDivisionReceiver>()
                        .eq(ShopDivisionReceiver::getShopId, SecurityUtils.getShopUser().getShopId())
                        .eq(ShopDivisionReceiver::getReceiverId, recordId));
        if (record == null) {
            throw new YamiShopBindException("记录不存在");
        }
        return ServerResponseEntity.success(record);
    }

    @Operation(summary = "根据分账组ID查询分账账号", description = "根据分账组ID查询分账账号")
    @Parameter(name = "receiverGroupId", description = "分账组ID", required = true)
    @GetMapping(value="/receiverGroupId/{receiverGroupId}")
    public ServerResponseEntity<List<ShopDivisionReceiver>> getDivisionReceiverByReceiverGroupId(@PathVariable("receiverGroupId") Long receiverGroupId) {
        List<ShopDivisionReceiver> records = shopDivisionReceiverService
                .list(new LambdaQueryWrapper<ShopDivisionReceiver>()
                        .eq(ShopDivisionReceiver::getShopId, SecurityUtils.getShopUser().getShopId())
                        .eq(ShopDivisionReceiver::getReceiverGroupId, receiverGroupId)
                        .eq(ShopDivisionReceiver::getState, 1));
        if (records.isEmpty()) {
            throw new YamiShopBindException("记录不存在");
        }
        return ServerResponseEntity.success(records);
    }


    @Operation(summary = "新增分账接收账号", description = "新增分账接收账号")
    @Parameters({
            @Parameter(name = "accName", description = "接收方姓名", required = true),
            @Parameter(name = "accNo", description = "接收方账号", required = true),
            @Parameter(name = "accType", description = "账接收账号类型: 0-个人(对私) 1-商户(对公)", required = true),
            @Parameter(name = "divisionProfit", description = "分账比例", required = true),
            @Parameter(name = "receiverAlias", description = "接收者账号别名", required = true),
            @Parameter(name = "receiverGroupId", description = "组ID（便于商户接口使用）", required = true),
            @Parameter(name = "relationType", description = "分账关系类型（参考微信）， 如： SERVICE_PROVIDER 服务商等", required = true),
            @Parameter(name = "relationTypeName", description = "当选择自定义时，需要录入该字段。 否则为对应的名称", required = true)
    })
    @PostMapping
    public ServerResponseEntity<Void> add(@RequestBody ShopDivisionReceiver shopDivisionReceiver) {
        ShopDivisionReceiverGroup group = shopDivisionReceiverGroupService.findByIdAndShopId(shopDivisionReceiver.getReceiverGroupId(), SecurityUtils.getShopUser().getShopId());
        if(group == null){
            throw new YamiShopBindException("商户分账账号组不存在，请检查或进入商户平台进行创建操作");
        }
        shopDivisionReceiver.setReceiverGroupName(group.getReceiverGroupName());
        shopDivisionReceiver.setShopId(SecurityUtils.getShopUser().getShopId());
        shopDivisionReceiver.setDivisionProfit(shopDivisionReceiver.getDivisionProfit().divide(new BigDecimal(100)));
        if(shopDivisionReceiver.getDivisionProfit().compareTo(BigDecimal.ZERO) <= 0  || shopDivisionReceiver.getDivisionProfit().compareTo(BigDecimal.ONE) > 1){
            throw new YamiShopBindException("账号分账比例有误, 配置值为[0.0001~1.0000]");
        }
        shopDivisionReceiver.setRelationTypeName(getRelationTypeName(shopDivisionReceiver.getRelationType())); //关系名称
        shopDivisionReceiver.setState(YES);
        shopDivisionReceiver.setBindSuccessTime(new Date());
        shopDivisionReceiver.setCreateTime(new Date());
        shopDivisionReceiverService.save(shopDivisionReceiver);
        return ServerResponseEntity.success();
    }

    @Operation(summary = "更新分账接收账号", description = "更新分账接收账号")
    @Parameters({
            @Parameter(name = "recordId", description = "分账接收者ID", required = true),
            @Parameter(name = "accName", description = "接收方姓名", required = true),
            @Parameter(name = "accNo", description = "接收方账号", required = true),
            @Parameter(name = "accType", description = "账接收账号类型: 0-个人(对私) 1-商户(对公)", required = true),
            @Parameter(name = "appId", description = "应用ID", required = true),
            @Parameter(name = "divisionProfit", description = "分账比例", required = true),
            @Parameter(name = "ifCode", description = "支付接口代码", required = true),
            @Parameter(name = "receiverAlias", description = "接收者账号别名", required = true),
            @Parameter(name = "receiverGroupId", description = "组ID（便于商户接口使用）", required = true),
            @Parameter(name = "relationType", description = "分账关系类型（参考微信）， 如： SERVICE_PROVIDER 服务商等", required = true),
            @Parameter(name = "relationTypeName", description = "当选择自定义时，需要录入该字段。 否则为对应的名称", required = true)
    })
    @PutMapping(value="/{recordId}")
    public ServerResponseEntity<Void> update(@PathVariable("recordId") Long recordId, @RequestBody ShopDivisionReceiver shopDivisionReceiver) {
        if(shopDivisionReceiver.getDivisionProfit() != null){
            shopDivisionReceiver.setDivisionProfit(shopDivisionReceiver.getDivisionProfit().divide(new BigDecimal(100)));
        }
        if(shopDivisionReceiver.getReceiverGroupId() != null){
            ShopDivisionReceiverGroup groupRecord = shopDivisionReceiverGroupService.findByIdAndShopId(shopDivisionReceiver.getReceiverGroupId(), SecurityUtils.getShopUser().getShopId());
            if (groupRecord == null) {
                throw new YamiShopBindException("账号组不存在");
            }
            shopDivisionReceiver.setReceiverGroupId(groupRecord.getReceiverGroupId());
            shopDivisionReceiver.setReceiverGroupName(groupRecord.getReceiverGroupName());
        }
        shopDivisionReceiver.setUpdateTime(new Date());
        LambdaUpdateWrapper<ShopDivisionReceiver> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(ShopDivisionReceiver::getReceiverId, recordId);
        updateWrapper.eq(ShopDivisionReceiver::getShopId, SecurityUtils.getShopUser().getShopId());
        shopDivisionReceiverService.update(shopDivisionReceiver, updateWrapper);
        return ServerResponseEntity.success();
    }

    @Operation(summary = "删除分账接收账号", description = "删除分账接收账号")
    @Parameter(name = "recordId", description = "分账接收者ID", required = true)
    @DeleteMapping(value="/{recordId}")
    public ServerResponseEntity<Void> del(@PathVariable("recordId") Long recordId) {
        ShopDivisionReceiver record = shopDivisionReceiverService.getOne(new LambdaQueryWrapper<ShopDivisionReceiver>()
                .eq(ShopDivisionReceiver::getReceiverGroupId, recordId).eq(ShopDivisionReceiver::getShopId, SecurityUtils.getShopUser().getShopId()));
        if (record == null) {
            throw new YamiShopBindException("记录不存在");
        }
        shopDivisionReceiverService.removeById(recordId);
        return ServerResponseEntity.success();
    }

    public String getRelationTypeName(String relationType){

        if("PARTNER".equals(relationType)){
            return "合作伙伴";
        }else if("SERVICE_PROVIDER".equals(relationType)){
            return "服务商";
        }else if("STORE".equals(relationType)){
            return "门店";
        }else if("STAFF".equals(relationType)){
            return "员工";
        }else if("STORE_OWNER".equals(relationType)){
            return "店主";
        }else if("HEADQUARTER".equals(relationType)){
            return "总部";
        }else if("BRAND".equals(relationType)){
            return "品牌方";
        }else if("DISTRIBUTOR".equals(relationType)){
            return "分销商";
        }else if("USER".equals(relationType)){
            return "用户";
        }else if("SUPPLIER".equals(relationType)){
            return "供应商";
        }
        return null;
    }

}
